﻿Imports System
Imports System.IO
Imports Microsoft.Build.Framework
Imports Microsoft.Build.Utilities
Imports System.Text
Imports System.Globalization

Public Class FixRiaTask
    Inherits Task

    <Required>
    Public Property ServerProject As String

    <Required>
    Public Property ClientOutputPath As String

    <Required>
    Public Property RootNamespace As String

    Public Overrides Function Execute() As Boolean
        Try
            ' read the existing file and split out the list of references & timestamps
            Dim fileName As String = ClientOutputPath & RootNamespace & ".RiaServerRefs.txt"

            Dim assemblyString As String
            Using sr As New StreamReader(fileName)
                assemblyString = sr.ReadToEnd
            End Using

            Dim detailsList() As String = assemblyString.Split(New Char() {";", ","})

            ' for any references that are relative, determine the absolute path and get the last write time
            ' since the existing code doesn't do that properly

            Dim serverPath As String = Path.GetDirectoryName(ServerProject)
            Dim sb As New StringBuilder
            Dim fixedDates As Boolean = False

            For i = 0 To detailsList.Count - 2 Step 2 ' the last element is an empty string
                Dim absolutePath As String = Path.GetFullPath(Path.Combine(serverPath, detailsList(i)))
                Dim currentTime As String = String.Format(CultureInfo.InvariantCulture, "{0}", File.GetLastWriteTime(absolutePath))

                If Not currentTime.Equals(detailsList(i + 1)) Then
                    sb.AppendFormat("{0},{1};", {detailsList(i), currentTime})
                    fixedDates = True
                Else
                    sb.AppendFormat("{0},{1};", {detailsList(i), detailsList(i + 1)})
                End If
            Next

            ' write out a new file

            If fixedDates Then
                Using newFile As New StreamWriter(fileName, False)
                    newFile.Write(sb.ToString)
                End Using
            End If

            Return True

        Catch e As Exception
            Return False
        End Try
    End Function
End Class




